/*
 *Copyright (c) 2024 Black Sesame Technologies
 *
 *Licensed under the Apache License, Version 2.0 (the "License");
 *you may not use this file except in compliance with the License.
 *You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 *Unless required by applicable law or agreed to in writing, software
 *distributed under the License is distributed on an "AS IS" BASIS,
 *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *See the License for the specific language governing permissions and
 *limitations under the License.
*/

#include "hscg_firmware_statistic.h"
#include "eth2can.h"

#define GTC_TIMESTAMP_L_REG 0x3000A088
#define GTC_TIMESTAMP_H_REG 0x3000A08C

#ifndef likely
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#endif

struct STATISTICS *statistics = (struct STATISTICS *)STATISTICS_SRAM_ADDR;

uint64 util_get_GTC_time64()
{
    return (((uint64)(*(uint32 *)GTC_TIMESTAMP_H_REG) << 32) | (*(uint32 *)GTC_TIMESTAMP_L_REG));
}

void init_statistics()
{
    memset(statistics, 0, sizeof(struct STATISTICS));
    statistics->magic_word = STATS_MAGIC_WORD;
    statistics->op_code = 0;

#ifdef STATISTICS_CODE_TIMESTAMP_ENABLE
    statistics_code_timestamp_init();
#endif
#ifdef STATISTICS_PACKET_TIMESTAMP_ENABLE
    statistics_packet_timestamp_init();
#endif
}

// A核向ETH核请求获取统计信息，刷新dcache
void get_statistics(const uint64 context, const ext_info_t *info)
{
    hprintf(DEBUG, "enter get_statistics\n");
    // invalidate_cache();
    can_s_server->switch0_can_gateway_server.reply_get_ETH_statistics(STATISTICS_SRAM_ADDR, 0, context);
}

void staticstics_run(void)
{
    uint32 op_code = statistics->op_code;
    uint32 user_cmd;
    uint32 user_para;

    if (likely(!op_code)) {
        return;
    }
    if (((op_code  >> STATS_KEY_OFFSET) & STATS_KEY_MASK) != STATS_OP_KEY) {
        statistics->op_code = 0;
        return;
    }

    user_para = (op_code >> STATS_PARA_OFFSET) & STATS_PARA_MASK;
    user_cmd = (op_code >> STATS_CMD_OFFSET) & STATS_CMD_MASK;
    switch(user_cmd) {
        case STATS_CMD_CLEAN_ALL:
            memset(&statistics->eth, 0, sizeof(struct port_stats));
            memset(statistics->can, 0, CAN_STATS_PORT_NUM*sizeof(struct port_stats));
            break;
        case STATS_CMD_CLEAN_CAN:
            if (!user_para)
                user_para = (1 << CAN_STATS_PORT_NUM) - 1;
            for (uint32 i = 0; i < CAN_STATS_PORT_NUM; i++) {
                if (user_para & (1 << i))
                    memset(statistics->can, 0, CAN_STATS_PORT_NUM*sizeof(struct port_stats));
            }
            break;
        case STATS_CMD_CLEAN_ETH:
            memset(&statistics->eth, 0, sizeof(struct port_stats));
            break;
        default:
            break;
    }
    statistics->op_code = 0;
}
